#include <ESP8266WiFi.h>

bool initStatus = false;
bool connetWifi = false;

void setup() {
  initInterface();
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  Serial.println("Setup done");
}

void loop() {
  appInit();
  // 提示灯亮三秒, 表示初始化已完成
  lightHigh3s();
  delay(10);
}

void appInit() {
  if(connetWifi) {
    Serial.println("Wifi connet");
  } else {
    connetWifiFunc();
  }
}

// 初始化接口
void initInterface() {
  pinMode(LED_BUILTIN, OUTPUT);
  delay(10);
  digitalWrite(LED_BUILTIN, LOW);
}

// 连接wifi
void connetWifiFunc() {
  Serial.println("Scan start");

  // 扫描网络
  int n = WiFi.scanNetworks();
  Serial.println("Scan done");
  if (n == 0) {
    Serial.println("No networks found");
  } else {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i) {
      // 打印网络列表
      Serial.print(i);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
    }
  }

  Serial.println("Enter the number of the network you want to connect to:");
  while (Serial.available() == 0) {
    // 等待用户输入, 指示灯常亮
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
  }
  int netIndex = Serial.parseInt(); // 从用户那里读取网络索引
  if (Serial.available() > 0) {     // 确保缓冲区被清空
    Serial.read();                   // 读取并丢弃缓冲区中的剩余字符（通常是换行符或回车符）
  }

  // 使用String对象来存储SSID
  String ssid = WiFi.SSID(netIndex);
  Serial.println("SSID: ");
  Serial.println(ssid);
  
  // 等待用户输入密码
  Serial.println("Enter the password for the network:");
  while (Serial.available() == 0) {
    // 等待用户输入, 指示灯常亮
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
  }
  String password = Serial.readStringUntil('\n'); // 读取密码直到换行符
  password.trim(); // 移除字符串两端的空白字符

  // 连接WiFi
  Serial.print("Connecting to ");
  Serial.println(ssid);
  Serial.print("Use password ");
  Serial.println(password);
  WiFi.begin(ssid, password);

  // 检查连接状态
  while (WiFi.status() != WL_CONNECTED) {
    delay(10);
    // 连接中, 提示灯高速闪烁
    Serial.print(".");
    lightHighLoop();
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  connetWifi = true;
}

// 提示灯慢闪烁
void lightLowLoop() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(3000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(3000);
}

// 提示灯高速闪烁
void lightHighLoop() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
}

// 提示灯常量
void lightHigh() {
  digitalWrite(LED_BUILTIN, HIGH);
}

// 提示灯长亮3秒
void lightHigh3s() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(3000);
  digitalWrite(LED_BUILTIN, LOW);
}

